<script lang="ts" setup>
import { ref, h, reactive, onMounted,onBeforeMount } from "vue";
import { ReVxeGrid } from "@/components/ReVxeTable";
import { VxeGridPropTypes, VxeUI } from "vxe-table";
import { VxeFormProps, VxeButton,VxeCheckbox,VxeImage } from "vxe-pc-ui";
import { ElMessage } from "element-plus";
import { exportFile } from '@/api/export';
import { downloadFile } from '@/api/file';
import { baseUrlApi } from "@/api/utils";
import recordDetail from "./components/recordDetail.vue";
import uploadRecord from "./components/uploadRecord.vue";
import { invoiceOrderState,querylistBackstageTax,auditBackstage } from "@/api/invoice/invoice";
import {
  MerchantsInfoByTaxSourcesId,
} from "@/api/welcome";
import { useRouter,useRoute } from "vue-router";
const router = useRouter();
const route = useRoute();
const reVxeGridRef = ref();
let taxSourcesId = Number(sessionStorage.getItem("taxSourcesId"))
onMounted(() => {
  getstate()
  getMerchantsInfoByTaxSourcesId( taxSourcesId )
  setTimeout(() => {
    if (route.query?.merchantsInfoId) {
      formOptions.data.merchantsInfoId = Number(route.query.merchantsInfoId);
      handleSearch();
    }
  }, 2000);
});
interface RestaurantItem {
  id: number
  value: string
}
const listMerchantsInfoByTaxSourcesId = ref<RestaurantItem[]>([]);
const getMerchantsInfoByTaxSourcesId = (taxSourcesId?:
  number): void => {
  MerchantsInfoByTaxSourcesId(taxSourcesId).then((res: any) => {
    listMerchantsInfoByTaxSourcesId.value = res.data;
  });
};
// 开票状态
const stateOptions = ref<any[]>();
const getstate = () => {
  invoiceOrderState().then((res: any) => {
    stateOptions.value = res.data;
  });
};
// 票据类型
const typeOptions = ref<any[]>([
  {
    label: "纸质发票",
    value: 1
  },
  {
    label: "电子发票",
    value: 2
  }
]);
// 发票类型
const bankOptions = ref<any[]>([
  {
    label: "增值税专用发票",
    value: 1
  },
  {
    label: "增值税普票发票",
    value: 0
  }
]);
// 开票类型
const whetherOptions = ref<any[]>([
  {
    label: "预开票",
    value: 1
  },
  {
    label: "正常开票",
    value: 0
  }
]);
const columns: VxeGridPropTypes.Columns<any> = [
  {
    title: "开票编号",
    field: "invoiceOrderNumber",
    align: "center",
    minWidth: 60,
    showOverflow: true
  },
  {
    title: "商户名称",
    field: "taxSourcesIdDisplay",
    align: "center",
    minWidth: 80,    
  }, 
  {
    title: "税源地名称",
    field: "merchantsName",
    align: "center",
    minWidth: 80,    
  }, 
  {
    title: "申请时间",
    field: "createTime",
    align: "center",
    minWidth: 60,    
  }, 
  {
    title: "开票金额（元）",
    field: "amountOfCanBeInvoiced",
    align: "center",
    minWidth: 60,    
  }, 
  {
    title: "发票抬头",
    field: "merchantsInfoIdDisplay",
    align: "center",
    minWidth: 60,    
  }, 
  {
    title: "发票类型",
    field: "invoiceTypeDisplay",
    align: "center",
    minWidth: 60, 
    slots:{
      default: ({ row }) => {
        if (row.invoiceTypeDisplay) {
          if(row.invoiceType == 0){
            return h(VxeButton,           
              {           
                    status: "primary",
                    mode: "button",
                     size: "mini",
                     plain:true,
                    content:row.invoiceTypeDisplay,
              });
             
          }else if(row.invoiceType == 1){
               return h(VxeButton,           
                  {           
                        status: "danger",
                        mode: "button",
                        size: "mini",
                         plain:true,
                        content:row.invoiceTypeDisplay,
                  });
          }          
      }
    }
    }   
  },
  {
    title: "发票备注",
    field: "remark",
    align: "center",
    minWidth: 60,    
  },
  {
    title: "开票类型",
    field: "whetherInvoiceDisplay",
    align: "center",
    minWidth: 60,    
  },
  {
    title: "票据类型",
    field: "typeOfInvoiceIssuedDisplay",
    align: "center",
    minWidth: 60,    
  },
  {
    title: "开票类目",
    field: "categoryOfInvoice",
    align: "center",
    minWidth: 60,    
  },
  {
    title: "开票状态",
    field: "invoiceOrderStateDisplay",
    align: "center",
    minWidth: 60,    
  },
  {
    title: "驳回原因",
    field: "reAuditRejectRemark",
    align: "center",
    minWidth: 60,    
  },
  {
    title: "发票照片",
    field: "invoiceUrl",
    align: "center",
    minWidth: 100,
    slots: {
      default: ({ row }) => {
        if (row.invoiceUrl) {
          return h(VxeImage, {
            src: `${row.invoiceUrl}`,
            width: "100",
            urlList: `[${row.invoiceUrl}]`
          });
        }
      }
    }
  },
  {
    title: "操作",
    field: "operate",
    align: "center",
    minWidth: 140,
    fixed: `right`,
    slots: {
      default: ({ row }) => {
        let list = [
          h(VxeButton, {
            status: "primary",
            mode: "text",
            size: "mini",
            content: "查看",
            onClick() {
              recordDetailRef.value.showAddModal(row.id);
            }
          }),
          h(VxeButton, {
            status: "primary",
            mode: "text",
            size: "mini",
            content: "上传发票",
            async onClick() {
              uploadRecordRef.value.showAddModal(row.id);
            }
          }),
          h(VxeButton, {
            status: "primary",
            mode: "text",
            size: "mini",
            content: "作废",
            async onClick() {
              const type = await VxeUI.modal.confirm("请确认是否作废该发票？");
              if (type == "confirm") {
                chnagestateZuoFei(row.id, 8);
              }
            }
          }),
          h(VxeButton, {
              status: "primary",
              mode: "text",
              size: "mini",
              content: "审核通过",
              async onClick() {
                const type = await VxeUI.modal.confirm("请确认是否审核通过？");
                if (type == "confirm") {
                  chnagestate(row.id, 3);
                }
              }
            }),
            h(VxeButton, {
              status: "primary",
              mode: "text",
              size: "mini",
              content: "审核驳回",
              onClick() {
                remark.value = "";
                dialogTableVisible.value = true;
                dialogId.value = row.id;
              }
            }),
        ];
        if (row.invoiceOrderState == 3) {
          return [list[0], list[1], list[2]];
        } else if (row.invoiceOrderState == 7) {
          //已完成 展示 查看 作废
          return [list[0], list[2]];
        } else if(row.invoiceOrderState == 0) {
          //待审核 展示 查看 审核通过 审核驳回
          return [list[0],list[3], list[4]];
        }
        else {
          return [list[0]];
        }
      }
    }
  }
   
];
// 筛选相关
const formRef = ref();
interface FormDataVO {
  merchantsInfoId: string;//商户名称
  taxSourcesId: number | string; // 税源地 
  invoiceType: string; //通道名称
  invoiceOrderState: number | string; // 状态
  typeOfInvoiceIssued: string | number;
  whetherInvoice: string | number; //开票类型
  timeRang: any[];
  createTimeStart: string;
  createTimeEnd: string;
  
}
const formOptions = reactive<VxeFormProps<FormDataVO>>({
  data: {
    merchantsInfoId: '',
    taxSourcesId: taxSourcesId,
    invoiceType: "",
    invoiceOrderState: "",
    typeOfInvoiceIssued: "",
    whetherInvoice: "",
    timeRang: [],
    createTimeStart: "",
    createTimeEnd: "",
  },
  items: [
    {
      field: "merchantsInfoId",
      title: "",
      span: 4,
      itemRender: {},
      slots: { default: "merchantsInfoId" }
    },    
    {
      field: "invoiceOrderState",
      title: "",
      span: 4,
      itemRender: {},
      slots: { default: "invoiceOrderState" }
    },
    {
      field: "invoiceType",
      title: "",
      span: 4,
      itemRender: {},
      slots: { default: "invoiceType" }
    },
    {
      field: "typeOfInvoiceIssued",
      title: "",
      span: 4,
      itemRender: {},
      slots: { default: "typeOfInvoiceIssued" }
    },
    {
      field: "whetherInvoice",
      title: "",
      span: 4,
      itemRender: {},
      slots: { default: "whetherInvoice" }
    },    
    {
      field: "timeRang",
      title: "",
      span: 6,
      itemRender: {},
      slots: { default: "timeRang" }
    },       
    { align: "left", span: 4, slots: { default: "active" } }
  ]
});
// 重置内容
const handleInitialFormParams = () => {
  formOptions.data = <FormDataVO>{
    taxSourcesId: '',
    merchantsInfoId: '',
    invoiceType: "",
    invoiceOrderState: "",
    typeOfInvoiceIssued: "",
    whetherInvoice: "",
    timeRang: [],
    createTimeStart: "",
    createTimeEnd: "",
  };
};
const handleSearch = () => {
  if (formOptions.data?.timeRang?.length) {
    formOptions.data.createTimeStart = formOptions.data.timeRang[0];
    formOptions.data.createTimeEnd = formOptions.data.timeRang[1];
  } else {
    formOptions.data.createTimeStart = "";
    formOptions.data.createTimeEnd = "";
  }
  delete formOptions.data.timeRang;
  reVxeGridRef.value.loadData();
};
const handleReset = async () => {
  await handleInitialFormParams();
  reVxeGridRef.value.loadData("reset");
};

const handleView = (record: Recordable) => {
  
};
// 查看详情
const recordDetailRef = ref();
// 上传发票
const uploadRecordRef = ref();
//作废
const chnagestateZuoFei = (id: number, type: number) => {
  auditBackstage({
    id: id,
    invoiceOrderState: type
  }).then(res => {
    ElMessage.success("操作成功!");
    handleSearch();
  });
};
const dialogTableVisible = ref<boolean>(false);
const dialogId = ref<number | string>();
const remark = ref<number | string>();
const chnagestate = (id: number | string, type: number) => {
  refundAudit({
    id: id,
    state: type,
    remark: remark.value,
    refundVoucher: form.refundVoucher
  }).then(res => {
    handleSearch();
  });
};
// 关闭驳回弹窗
const toclose = () => {
  dialogTableVisible.value = false;
  dialogId.value = "";
  remark.value = "";
};
const functions: Record<string, string> = {
  add: "platform.client.index.add",
  edit: "platform.client.index.edit",
  view: "platform.client.index.view",
  delete: "platform.client.index.delete"
};
const toexport = () => {
  if (formOptions.data?.timeRang?.length) {
    formOptions.data.createTimeStart = formOptions.data.timeRang[0];
    formOptions.data.createTimeEnd = formOptions.data.timeRang[1];
  } else {
    formOptions.data.createTimeStart = '';
    formOptions.data.createTimeEnd = '';
  }
  let data = formOptions.data;
  delete data['timeRang']
  // exportFile
  exportFile(baseUrlApi("business/average_user_merchants_deal/listBackstageExport"),data)
}
</script>
<template>
  <div>
    <el-card :shadow="`never`">
      <vxe-form ref="formRef" v-bind="formOptions">
        <template #merchantsInfoId="{ data }">
          <el-select
            clearable
            placeholder="请选择商户名称"
            v-model="data.merchantsInfoId"
          >
            <el-option
              v-for="(item, index) in listMerchantsInfoByTaxSourcesId"
              :key="index"
              :label="item.value"
              :value="item.id"
            ></el-option>
          </el-select>
        </template>
        <template #invoiceOrderState="{ data }">
          <el-select
            clearable
            placeholder="请选择开票状态"
            v-model="data.invoiceOrderState"
          >
            <el-option
              v-for="(item, index) in stateOptions"
              :key="index"
              :label="item.desc"
              :value="item.code"
            ></el-option>
          </el-select>
        </template>
        <template #invoiceType="{ data }">
          <el-select
            clearable
            placeholder="请选择发票类型"
            v-model="data.invoiceType"
          >
            <el-option
              v-for="(item, index) in bankOptions"
              :key="index"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </template>
        <template #typeOfInvoiceIssued="{ data }">
          <el-select
            clearable
            placeholder="请选择票据类型"
            v-model="data.typeOfInvoiceIssued"
          >
            <el-option
              v-for="(item, index) in typeOptions"
              :key="index"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </template>
        <template #whetherInvoice="{ data }">
          <el-select
            clearable
            placeholder="请选择开票类型"
            v-model="data.whetherInvoice"
          >
            <el-option
              v-for="(item, index) in whetherOptions"
              :key="index"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </template>
        <template #timeRang="{ data }">
          <el-date-picker
            clearable
            style="width: 100%"
            v-model="data.timeRang"
            type="daterange"
            range-separator="-"
            value-format="YYYY-MM-DD"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          />
        </template>
        <template #active>
          <el-button @click="handleSearch" native-type="submit" type="primary"
            >搜索</el-button
          >
          <el-button @click="handleReset" native-type="reset">重置</el-button>          
        </template>
      </vxe-form>
      <div class="mt-3">
        <el-button @click="toexport" type="primary">导出</el-button>
      </div>
    </el-card>
    <el-card :shadow="`never`" class="table-card">
      <ReVxeGrid
        ref="reVxeGridRef"
        :request="querylistBackstageTax"
        :functions="functions"
        :searchParams="formOptions.data"
        :columns="columns"
        :action="false"
        @handleView="handleView"         
      />
    </el-card>
    <!-- 审核驳回 -->
    <el-dialog v-model="dialogTableVisible" title="审核驳回" width="800">
      <div>
        <el-input
          type="textarea"
          v-model="remark"
          placeholder="请输入驳回原因"
        ></el-input>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="toclose">取消</el-button>
          <el-button type="primary" @click="tosub"> 确认 </el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 上传发票 -->
    <uploadRecord ref="uploadRecordRef" @reload="handleSearch"></uploadRecord>
    <recordDetail ref="recordDetailRef" @reload="handleSearch" />
  </div>
</template>
<style>
</style>
